﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Company.Core.Logger
{
    public class Logs
    {
        public static string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
        public static object logLocker = new();

        protected static void WriteLog(string content)
        {
            lock (logLocker)
            {
                try
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    
                    string logFile = Path.Combine(path, DateTime.Now.ToString("yyyy-MM-dd") + ".log");
                    
                    // 使用 AppendAllText 而不是 StreamWriter，确保多线程安全
                    string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} {content}{Environment.NewLine}";
                    File.AppendAllText(logFile, logEntry, Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    // 避免日志记录本身出错导致程序崩溃
                    System.Diagnostics.Debug.WriteLine($"日志写入失败：{ex.Message}");
                }
            }
        }

        public static void Debug(string content)
        {
            WriteLog("[DEBUG] " + content);
        }

        public static void Info(string content)
        {
            WriteLog("[INFO] " + content);
        }

        public static void Warning(string content)
        {
            WriteLog("[WARNING] " + content);
        }

        public static void Error(string content)
        {
            WriteLog("[ERROR] " + content);
        }

        public static void Error(Exception ex)
        {
            WriteLog("[EXCEPTION] " + ex.Message + Environment.NewLine + ex.StackTrace);
        }
        
        /// <summary>
        /// 记录用户操作日志
        /// </summary>
        public static void UserAction(string userName, string action)
        {
            WriteLog($"[USER_ACTION] 用户[{userName}] {action}");
        }
    }
}
